<template>
  <transition name="toast-fade">
    <div v-if="visible" class="toast-container" :class="type">
      <div class="toast-content">
        <i class="toast-icon" :class="iconClass"></i>
        <span class="toast-message">{{ message }}</span>
      </div>
    </div>
  </transition>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, computed } from 'vue';

const props = defineProps<{
  message: string;
  type?: 'success' | 'error' | 'warning' | 'info';
  duration?: number;
  visible: boolean;
}>();

const emit = defineEmits<{
  (e: 'close'): void;
}>();

const visible = ref(props.visible);
let timer: number | null = null;

// 根据类型确定图标
const iconClass = computed(() => {
  switch (props.type) {
    case 'success':
      return 'fa fa-check-circle';
    case 'error':
      return 'fa fa-times-circle';
    case 'warning':
      return 'fa fa-exclamation-triangle';
    case 'info':
    default:
      return 'fa fa-info-circle';
  }
});

// 监听visible属性变化
watch(() => props.visible, (newVal) => {
  visible.value = newVal;
  if (newVal && props.duration !== 0) {
    startTimer();
  }
});

// 监听消息变化，如果消息变化且toast可见，重置定时器
watch(() => props.message, () => {
  if (visible.value && props.duration !== 0) {
    clearTimer();
    startTimer();
  }
});

// 启动定时器
const startTimer = () => {
  if (props.duration !== 0) {
    clearTimer();
    timer = window.setTimeout(() => {
      close();
    }, props.duration || 3000);
  }
};

// 清除定时器
const clearTimer = () => {
  if (timer) {
    clearTimeout(timer);
    timer = null;
  }
};

// 关闭toast
const close = () => {
  visible.value = false;
  emit('close');
};

onMounted(() => {
  if (visible.value && props.duration !== 0) {
    startTimer();
  }
});

onUnmounted(() => {
  clearTimer();
});
</script>

<style scoped>
.toast-container {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 9999;
  padding: 10px 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
  display: flex;
  align-items: center;
  min-width: 300px;
  max-width: 80%;
}

.toast-content {
  display: flex;
  align-items: center;
  width: 100%;
}

.toast-icon {
  margin-right: 10px;
  font-size: 16px;
}

.toast-message {
  font-size: 14px;
  line-height: 1.5;
  word-break: break-word;
}

/* 类型样式 */
.success {
  background-color: #f0f9eb;
  border: 1px solid #e1f3d8;
  color: #67c23a;
}

.error {
  background-color: #fef0f0;
  border: 1px solid #fde2e2;
  color: #f56c6c;
}

.warning {
  background-color: #fdf6ec;
  border: 1px solid #faecd8;
  color: #e6a23c;
}

.info {
  background-color: #f4f4f5;
  border: 1px solid #e9e9eb;
  color: #909399;
}

/* 动画效果 */
.toast-fade-enter-active,
.toast-fade-leave-active {
  transition: opacity 0.3s, transform 0.3s;
}

.toast-fade-enter-from,
.toast-fade-leave-to {
  opacity: 0;
  transform: translateX(-50%) translateY(-20px);
}
</style>